package com.mysoft.gfyx.common.aspect;

import com.alibaba.fastjson.JSON;
import com.mysoft.gfyx.common.util.LogUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

@Aspect
@Component
public class LogAspect {

    @Autowired
    private LogUtil logUtil;

    private Long batchNo;

    //切入点，用于匹配方法执行的切入点。切入点是com.mysoft.gfyx.marketdevelop.controller包下的所有请求，多个切入点用or
    @Pointcut("execution(* com.mysoft.gfyx.marketdevelop.controller.*.*(..))")

    //Point签名
    public void log() {

    }

    @Before("log()")    //前置增强
    public void doBefore(JoinPoint joinPoint) {
        try {
            this.batchNo = System.currentTimeMillis();
            //获取request请求
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attributes != null) {
                HttpServletRequest request = attributes.getRequest();
                //通过请求获取url,ip
                String url = request.getRequestURL().toString();
                String ip = request.getRemoteAddr();
                //获取方法所在的包名和类名
                String classMethod = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
                //获取请求的参数
                Object[] args = joinPoint.getArgs();
                if (args.length > 0) {
                    logUtil.info("api-request:batch-no:" + this.batchNo.toString() + ",url:" + url, JSON.toJSONString(args[0]));
                }
            }
        } catch (Exception e) {
            logUtil.error("日志AOP异常", e);
        }

    }

    @After("log()")     //标识为一个后置增强方法，不管程序会不会抛出异常都会执行。
    public void doAfter() {
    }

    //后置增强，在方法正常退出的时候执行
    @AfterReturning(returning = "result", pointcut = "log()")
    public void doAfterRuturn(Object result) {
        try {
            logUtil.info("api-response:batch-no:" + this.batchNo.toString(), JSON.toJSONString(result));
        } catch (Exception e) {
            logUtil.error("日志AOP异常", e);
        }
    }

}